<script setup>
import { onMounted, ref, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'
const chartRef = ref(null)
let myChart = null
let resizeObserver = null
onMounted(() => {
    if (chartRef.value) {
        myChart = echarts.init(chartRef.value)
        const option = {
            tooltip: {
                backgroundColor: 'rgba(37,41,56,.8)',
                borderColor: '#02a6b5',
                textStyle: {
                    color: '#fff'
                },
                formatter: function (params) {
                    return params.seriesName + '</br> ' + params.name + ': ' + params.value + ' (' + Math.round(params.percent) + '%)';
                }
            },
            legend: {
                bottom: '0%',
                left: '0%',
                textStyle: {
                    color: '#8589a5',   // 设置图例文字颜色
                    fontSize: 10
                }
            },
            series: [
                {
                    name: '地区分布',
                    type: 'pie',
                    radius: [15, 75],
                    center: ['50%', '50%'],
                    roseType: 'area',
                    itemStyle: {
                        borderRadius: 8
                    },
                    data: [
                        { value: 26, name: '北京', itemStyle: { color: '#60cda0' } },
                        { value: 24, name: '山东', itemStyle: { color: '#ff9591' } },
                        { value: 25, name: '河北', itemStyle: { color: '#ffae8b' } },
                        { value: 20, name: '河南', itemStyle: { color: '#00a5ff' } },
                        { value: 25, name: '浙江', itemStyle: { color: '#aefdca' } },
                        { value: 30, name: '四川', itemStyle: { color: '#37d8ff' } },
                        { value: 42, name: '湖北', itemStyle: { color: '#1facff' } }
                    ]
                }
            ]
        };

        // 设置图表配置
        myChart.setOption(option)

        // 使用 ResizeObserver 监听容器大小变化
        if (window.ResizeObserver) {
            resizeObserver = new ResizeObserver(() => {
                myChart.resize()
            })
            resizeObserver.observe(chartRef.value)
        } else {
            // 降级方案：监听窗口大小变化
            window.addEventListener('resize', handleResize)
        }
    }
})
// 处理窗口大小变化
const handleResize = () => {
    if (myChart) {
        myChart.resize({
            animation: {
                duration: 300
            }
        })
    }
}

// 组件卸载时清理事件监听器
onUnmounted(() => {
    if (resizeObserver && chartRef.value) {
        resizeObserver.unobserve(chartRef.value)
        resizeObserver = null
    }

    window.removeEventListener('resize', handleResize)

    if (myChart) {
        myChart.dispose()
    }
})
</script>

<template>
    <div ref="chartRef" style="width: 100%; height: 240px;"></div>
</template>

<style lang="scss" scoped></style>
